<template>
  <el-config-provider :locale="zhCn">
    <div class="text-config">
      <!-- 主要内容区域 -->
      <div style="display: flex; gap: 2rem; height: calc(100vh); overflow: hidden">
        <div
          style="
            width: 75%;
            height: 100%;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            border-radius: 0.25rem;
            box-shadow: 0 0.125rem 0.75rem 0 rgba(0, 0, 0, 0.1);
          "
        >
          <div class="config-form">
            <div class="form-section">
              <div class="form-title">
                消息配置
                <el-tooltip content="配置可编辑的文本内容，支持多条文本消息管理" placement="top" effect="dark">
                  <el-icon class="tips-icon">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>
          </div>

          <div class="text-editor">
            <div class="editor-section">
              <el-form label-width="80px">
                <el-form-item label="文本内容" required>
                  <el-input v-model="currentText" type="textarea" :rows="6" placeholder="请输入文本内容" maxlength="200" show-word-limit />
                </el-form-item>
              </el-form>

              <div class="editor-actions">
                <el-button type="primary" @click="handleAddText">添加文本</el-button>
              </div>
            </div>

            <div class="text-list-section">
              <div class="preview-title" v-if="textList.length > 0">已添加消息列表</div>

              <div class="text-list">
                <el-card v-for="(text, index) in textList" :key="index" class="text-item">
                  <div class="text-header">
                    <div class="text-info">
                      <span class="text-type-tag">文本</span>
                      <div class="text-content" @click="handleEditText(index)">
                        {{ text }}
                      </div>
                    </div>
                    <div class="text-actions">
                      <div class="action-buttons">
                        <el-button type="primary" link @click="handleEditText(index)">
                          <el-icon><Edit /></el-icon>
                        </el-button>

                        <el-button type="danger" link @click="handleDeleteText(index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </div>
        <UserMessagePreview :messages="messageList" style="width: 25%; height: 100%; overflow: hidden" />
      </div>
    </div>
  </el-config-provider>

  <!-- 文本编辑弹窗 -->
  <el-dialog v-model="editDialogVisible" title="编辑文本" width="600px">
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="文本内容" required>
        <el-input v-model="editForm.text" type="textarea" :rows="6" placeholder="请输入文本内容" maxlength="200" show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Delete, Edit, QuestionFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import {
  getAuthenticationList,
  addAuthentication,
  updateAuthentication,
  deleteAuthentication,
  type AuthenticationInfo,
  type AuthenticationQueryParams
} from '@/api/userRate/friendVerify';
import UserMessagePreview from '@/components/MessagePreview/UserMessagePreview.vue';

// API响应接口
interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 当前输入的文本
const currentText = ref('');

// 文本列表
const textList = ref<string[]>([]);

// 验证消息列表（包含完整信息）
const authenticationList = ref<AuthenticationInfo[]>([]);

// 编辑相关
const editDialogVisible = ref(false);
const editForm = reactive({
  text: '',
  index: -1
});

// 获取用户信息
const getUserInfo = () => {
  const userInfo = localStorage.getItem('userInfo');
  return userInfo ? JSON.parse(userInfo) : {};
};

// 获取消息列表（使用friendVerify的接口）
const fetchMessageList = async () => {
  try {
    const userInfo = getUserInfo();
    if (!userInfo.username) {
      ElMessage.error('未获取到用户信息');
      return;
    }

    const params: AuthenticationQueryParams = {
      account: userInfo.username,
      current: 1,
      size: 1000 // 获取所有消息
    };

    const res = (await getAuthenticationList(params)) as unknown as ApiResponse<{ records: AuthenticationInfo[] }>;
    if (res.code === 200 && res.data) {
      // 保存完整的验证消息列表
      authenticationList.value = res.data.records;
      // 将验证消息转换为文本列表
      textList.value = res.data.records.map((item: AuthenticationInfo) => item.message);
    } else {
      ElMessage.error(res.msg || '获取消息列表失败');
    }
  } catch (error) {
    console.error('获取消息列表失败:', error);
    ElMessage.error('获取消息列表失败');
  }
};

// 添加文本
const handleAddText = async () => {
  if (!currentText.value.trim()) {
    ElMessage.warning('请输入文本内容');
    return;
  }

  if (currentText.value.length > 200) {
    ElMessage.warning('文本内容不能超过200个字符');
    return;
  }

  try {
    const userInfo = getUserInfo();
    if (!userInfo.username) {
      ElMessage.error('未获取到用户信息');
      return;
    }

    const data: AuthenticationInfo = {
      account: userInfo.username,
      message: currentText.value.trim()
    };

    const res = (await addAuthentication(data)) as unknown as ApiResponse;
    if (res.code === 200) {
      ElMessage.success('添加文本成功');
      currentText.value = '';
      // 重新获取消息列表
      fetchMessageList();
    } else {
      ElMessage.error(res.msg || '添加失败');
    }
  } catch (error) {
    console.error('添加文本失败:', error);
    ElMessage.error('添加失败');
  }
};

// 编辑文本
const handleEditText = (index: number) => {
  editForm.text = textList.value[index];
  editForm.index = index;
  editDialogVisible.value = true;
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!editForm.text.trim()) {
    ElMessage.warning('请输入文本内容');
    return;
  }

  if (editForm.text.length > 200) {
    ElMessage.warning('文本内容不能超过200个字符');
    return;
  }

  try {
    const userInfo = getUserInfo();
    if (!userInfo.username) {
      ElMessage.error('未获取到用户信息');
      return;
    }

    // 获取对应的验证消息记录
    const authItem = authenticationList.value[editForm.index];
    if (!authItem || !authItem.id) {
      ElMessage.error('未找到对应的记录');
      return;
    }

    const data = {
      id: authItem.id,
      account: userInfo.username,
      message: editForm.text.trim()
    };

    const res = (await updateAuthentication(data)) as unknown as ApiResponse;
    if (res.code === 200) {
      ElMessage.success('编辑文本成功');
      editDialogVisible.value = false;
      // 重新获取消息列表
      fetchMessageList();
    } else {
      ElMessage.error(res.msg || '编辑失败');
    }
  } catch (error) {
    console.error('编辑文本失败:', error);
    ElMessage.error('编辑失败');
  }
};

// 删除文本
const handleDeleteText = async (index: number) => {
  if (index < 0 || index >= textList.value.length) {
    return;
  }

  try {
    // 二次确认
    await ElMessageBox.confirm('确定要删除这条文本消息吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const userInfo = getUserInfo();
    if (!userInfo.username) {
      ElMessage.error('未获取到用户信息');
      return;
    }

    // 获取对应的验证消息记录
    const authItem = authenticationList.value[index];
    if (!authItem || !authItem.id) {
      ElMessage.error('未找到对应的记录');
      return;
    }

    const data = {
      id: authItem.id,
      account: userInfo.username
    };

    const res = (await deleteAuthentication(data)) as unknown as ApiResponse;
    if (res.code === 200) {
      ElMessage.success('删除文本成功');
      // 重新获取消息列表
      fetchMessageList();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    // 用户取消删除或其他错误
    if (error !== 'cancel') {
      console.error('删除文本失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 将文本列表转换为消息格式
const messageList = computed(() => {
  return textList.value.map((text) => ({
    type: 'text' as const,
    data: text,
    text: text
  }));
});

// 页面加载时获取数据
onMounted(() => {
  fetchMessageList(); // 获取消息列表
});
</script>

<style lang="scss" scoped>
.text-config {
  padding: 1.25rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
  border-radius: 0.5rem;
  box-shadow: 0 0.125rem 0.75rem 0 rgba(0, 0, 0, 0.1);

  .config-form {
    background: #fff;
    padding: 1.25rem;
    padding-bottom: 0;
    box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.05);

    .form-section {
      .form-title {
        font-size: 1.125rem;
        font-weight: 600;
        color: #303133;
        margin-bottom: 1.5rem;
        padding-bottom: 0.75rem;
        border-bottom: 0.0625rem solid #ebeef5;
        display: flex;
        align-items: center;
      }
    }
  }

  .text-editor {
    flex: 1;
    background: #fff;
    padding: 0 1.25rem;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .editor-section {
      margin-bottom: 1.5rem;

      .editor-actions {
        margin-top: 1rem;
        display: flex;
        justify-content: flex-end;
      }
    }

    .text-list-section {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;

      .preview-title {
        font-size: 1rem;
        font-weight: bold;
        color: #303133;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .text-list {
        flex: 1;
        overflow-y: auto;
        padding-right: 10px;
        padding: 10px;

        &::-webkit-scrollbar {
          width: 0.375rem;
        }

        &::-webkit-scrollbar-thumb {
          background-color: #c0c4cc;
          border-radius: 0.1875rem;
        }

        &::-webkit-scrollbar-track {
          background-color: #f5f7fa;
        }

        .text-item {
          margin-bottom: 0.75rem;
          transition: all 0.3s;
          border: 0.0625rem solid #ebeef5;
          border-radius: 0.5rem;
          overflow: hidden;

          &:hover {
            transform: translateY(-0.125rem);
            box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
          }

          :deep(.el-card__body) {
            padding: 1rem !important;
          }

          .text-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 1rem;

            .text-info {
              flex: 1;
              display: flex;
              align-items: flex-start;
              gap: 0.75rem;

              .text-type-tag {
                padding: 0.25rem 0.5rem;
                border-radius: 0.25rem;
                font-size: 0.75rem;
                font-weight: 500;
                white-space: nowrap;
                flex-shrink: 0;
                background-color: #e6f7ff;
                color: #1890ff;
              }

              .text-content {
                flex: 1;
                min-width: 0;
                font-size: 0.875rem;
                color: #606266;
                word-break: break-all;
                white-space: pre-wrap;
                line-height: 1.5;
                cursor: pointer;
                padding: 0.25rem;
                border-radius: 0.25rem;
                transition: all 0.3s;

                &:hover {
                  background-color: #f5f7fa;
                }
              }
            }

            .text-actions {
              flex-shrink: 0;

              .action-buttons {
                display: flex;
                gap: 0.5rem;
                align-items: center;

                .el-button {
                  padding: 0.25rem;

                  &.is-disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                  }

                  .el-icon {
                    font-size: 1rem;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

.tips-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
  font-size: 16px;

  &:hover {
    color: #409eff;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}
</style>
